/**
 * 文件：activity_login.java
 * 包名：com.ronri.ams;   --- 正式发布时需要修正
 * 说明：登录
 * 作者：MS During
 * 日期：2017/5/14
 * 历史：
 */
package com.ronri.ams;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.ams.bean.loginbean;
import com.ronri.common.UrlEncode;
import com.ronri.db.RemoteDataService;
import com.zhy.autolayout.AutoLayoutActivity;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class activity_login extends AutoLayoutActivity {

    private Button btnLogin = null;
    private EditText edUser = null;
    private EditText edPass = null;
    private Context mContext = null;
    private String mAccount = "";
    private String mPWD = "";
    private boolean mAutoLogin = false;
    private SharedPreferences mPref;


    private void setImmersionStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
//			getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    /****
     * 自动登录
     */
    private void AutoLogon(){
        mAccount = mPref.getString("account", "");
        mPWD = mPref.getString("password", "");
        mAutoLogin = mPref.getBoolean("autologin", false);

        if (mAutoLogin == true){
            Logon(mAccount, mPWD);
        }
    }

    /***
     * 登录处理
     * @param szAcc
     * @param szPwd
     */
    private void Logon(final String szAcc, final String szPwd)
    {
        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getLogin().getAddress());
        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("account", URLEncoder.encode(szAcc, "utf-8"));
            mParam.put("password", URLEncoder.encode(szPwd, "utf-8"));
            mParam.put("deviceid", "?????");
        }catch (Exception ex){

        }

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getLogin().getMethod(),
                new RemoteDataService.OnRemoteDataEvent(){
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
                        Log.i("test","login-->"+szString);
                        if(szString.isEmpty())
                            return;

//                        if(szString.contains("网络连接失败")){
//                            Toast.makeText(activity_login.this,"网络连接失败",Toast.LENGTH_SHORT).show();
//                            return;
//                        }
                        try{
                            loginbean login = JSON.parseObject(szString, loginbean.class);

                            if (login.isSuccess()){

                                SharedPreferences.Editor editor = mPref.edit();

                                editor.putString("account", szAcc);
                                editor.putString("password", szPwd);
                                editor.putBoolean("autologin", true);
                                editor.apply();

                                // 记录登录信息
                                InitApplication.LoginInfo = login;

                                finish();

                                Intent intent = new Intent(getBaseContext(), MainActivity.class);
                                startActivity(intent);
                            }else{
                                SharedPreferences.Editor editor = mPref.edit();

                                editor.putString("account", "");
                                editor.putString("password", "");
                                editor.putBoolean("autologin", false);
                                editor.apply();

                                // 提示错误信息
                                Toast.makeText(activity_login.this,login.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }catch (Exception ex){

                        }
                    }
                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if(nStatus == SystemEnvironmental.GetDataFromServerError){
                            Toast.makeText(activity_login.this,"网络连接失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setImmersionStatus();
        setContentView(R.layout.activity_login);

        //AutoLayout.getInstance().auto(this, true);

        mPref = getSharedPreferences("ronri", MODE_PRIVATE);

        mContext = this;
        btnLogin = (Button)findViewById(R.id.email_sign_in_button);
        edUser = (EditText)findViewById(R.id.login_user);
        edPass = (EditText)findViewById(R.id.login_pwd);

        if( InitApplication.LoginInfo!=null&&!InitApplication.LoginInfo.getData().getAccount().equals("")){
            edUser.setText(InitApplication.LoginInfo.getData().getAccount());
        }
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if((edUser == null) || (edPass == null)){
                    // 提示错误
                    return;
                }

                String szUser, szPass;

                szUser = edUser.getText().toString();
                szPass = edPass.getText().toString();

                if ((szUser.isEmpty() || (szPass.isEmpty()))){
                    // 提示错误
                    Toast.makeText(activity_login.this,"请输入用户名和密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                Logon(szUser, szPass);
            }
        });

        AutoLogon();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//
//        Drawable drawable= mBackground.getDrawable();
//        if(drawable instanceof BitmapDrawable){
//            Bitmap bmp = ((BitmapDrawable)drawable).getBitmap();
//            if (bmp != null && !bmp.isRecycled()){
//                mBackground.setImageBitmap(null);
//                bmp.recycle();
//                bmp=null;
//            }
//        }

        // 清空后台
        setContentView(R.layout.s_free_layout);

        System.gc();
        System.runFinalization();
    }
}
